package com.woniu.product.service.impl;

import cn.hutool.core.util.IdUtil;
import cn.hutool.core.util.ObjectUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;

import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.woniu.common.utils.PageParam;

import com.woniu.common.dto.UserCouponDTO;
import com.woniu.common.utils.JWTUtil;

import com.woniu.common.utils.ResponseData;
import com.woniu.common.utils.SnowflakeIdGenerator;
import com.woniu.product.dto.CouponAddDTO;
import com.woniu.product.dto.CouponQueryDTO;
import com.woniu.product.pojo.Coupon;
import com.woniu.product.pojo.CouponStatus;
import com.woniu.product.service.CouponService;
import com.woniu.product.mapper.CouponMapper;
import com.woniu.product.service.CouponStatusService;
import lombok.SneakyThrows;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;


import java.text.SimpleDateFormat;
import java.util.ArrayList;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;

import java.util.Date;
import java.util.List;
import java.util.Map;

/**
 * @author ltyipx
 * @description 针对表【coupon】的数据库操作Service实现
 * @createDate 2024-08-06 14:17:02
 */
@Service
public class CouponServiceImpl extends ServiceImpl<CouponMapper, Coupon> implements CouponService {
    @Autowired
    private CouponStatusService couponStatusService;

    @Autowired
    private CouponMapper couponMapper;

    @Autowired
    private HttpServletRequest request;

    @Override
    public List<Coupon> queryCoupon(String id) {
        List<Coupon> list = couponMapper.queryCoupon(id);
        return list;
    }

    @SneakyThrows
    @Override
    @Transactional
    public ResponseData getCoupon(String couponId) {
        Map<String, Object> userInfo = getUserInfo();
        String userId = userInfo.get("id").toString();
        CouponStatus byId = couponStatusService.ifHave(couponId, userId);
        //判断用户是否已经领取过这个优惠券了
        if (!ObjectUtil.isEmpty(byId)) {
            return new ResponseData().fail();
        }
        //往用户优惠券表添加一条数据
        Coupon coupon = couponMapper.queryCouponById(couponId);
        CouponStatus couponStatus = new CouponStatus();
        long id = IdUtil.getSnowflake().nextId();
        couponStatus.setId(String.valueOf(id));
        couponStatus.setUserCouponid(couponId);
        //TODO app用户登录信息，暂时写死，等写好登录功能再取userId
        couponStatus.setUserid(userId);
        couponStatus.setProductId(coupon.getProductId());
        couponStatus.setStatus(0);
        boolean save = couponStatusService.save(couponStatus);
        if (!save) {
            throw new RuntimeException();
        }
        return new ResponseData().success();
    }

    @Override
    public ResponseData<?> selCouponByCondition(PageParam<CouponQueryDTO> pageParam) {
        PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        List<Coupon> couponList = couponMapper.selCouponByCondition(pageParam.getParam());
        PageInfo<Coupon> couponPageInfo = new PageInfo<>(couponList);
        return new ResponseData<>().success(couponPageInfo);
    }

    @SneakyThrows
    @Override
    @Transactional
    public ResponseData<?> addCoupon(CouponAddDTO couponAddDTO) {
        ArrayList<Coupon> coupons = new ArrayList<>();
        for (String s : couponAddDTO.getProductId()) {
            Coupon coupon = new Coupon();
//            long l = new SnowflakeIdGenerator().nextId();
            long l = IdUtil.getSnowflake(1, 1).nextId();
            coupon.setId(String.valueOf(l));
            coupon.setProductId(s);
            coupon.setUsageAmount(couponAddDTO.getUsageAmount());
            coupon.setTotal(couponAddDTO.getTotal());
            coupon.setAvailable(1);
            coupon.setCondition(couponAddDTO.getCondition());
            coupon.setReason("不满足使用条件");
            coupon.setValue(couponAddDTO.getValue());
            coupon.setName(couponAddDTO.getCouponName());
            String startTime = couponAddDTO.getStartTime();
            SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
            Date startParse = simpleDateFormat.parse(startTime);
            coupon.setStartat(startParse);
            String endTime = couponAddDTO.getEndTime();
            Date endParse = simpleDateFormat.parse(endTime);
            coupon.setEndat(endParse);
            coupon.setCreateTime(new Date());
            coupons.add(coupon);
        }
        saveBatch(coupons);
        return new ResponseData<>().success();

    }

    @SneakyThrows
    @Override
    public ResponseData<?> queryMyCoupons(String[] productIds) {
        Map<String, Object> userInfo = getUserInfo();
        String userId = userInfo.get("id").toString();
        List<UserCouponDTO> list = couponMapper.queryMyCoupons(userId, productIds);
        return new ResponseData<>().success(list);
    }

    @Transactional
    @Override
    public ResponseData<?> stopCoupon(String couponId) {
        lambdaUpdate().eq(Coupon::getId, couponId)
                .set(Coupon::getAvailable, 0)
                .update();
        List<CouponStatus> couponStatusList = couponStatusService.lambdaQuery()
                .eq(CouponStatus::getUserCouponid, couponId)
                .list();
        if (couponStatusList.size() > 0) {
            couponStatusService.lambdaUpdate()
                    .eq(CouponStatus::getUserCouponid, couponId)
                    .set(CouponStatus::getStatus, 2)
                    .update();
        }
        return new ResponseData<>().success();
    }

    private Map<String, Object> getUserInfo() throws ParseException {
        String jwt = null;
        Cookie[] cookies = request.getCookies();
        for (Cookie cookie : cookies) {
            if ("jwt".equals(cookie.getName())) {
                jwt = cookie.getValue();
            }
        }
        Map<String, Object> userInfo = JWTUtil.getUserInfo(jwt);
        return userInfo;
    }
}




